package com.example.app;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

import com.getcapacitor.Logger;

import cn.wps.moffice.demo.util.Define;
import cn.wps.moffice.demo.util.SettingPreference;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;

public class SaveReceiver extends BroadcastReceiver {
	SettingPreference settingPreference;
	/**
	 * 接收wps关闭时发送的广播，同时记录关闭时的参数，以便下一次打开
	 */
    public void onReceive(Context context, Intent intent) {
//		Toast.makeText(context,"接收到关闭的广播",Toast.LENGTH_SHORT).show();
    	settingPreference = new SettingPreference(context);
    	String strFileId = settingPreference.getSettingParam("fileid","");
    	String strFileName = settingPreference.getSettingParam("filename","");
		String strFilePath = settingPreference.getSettingParam("filepath","");
		String uploadUrl = settingPreference.getSettingParam("uploadUrl","");

        boolean saveAs = intent.getExtras().getBoolean("SaveAs");
        String	packageName = intent.getExtras().getString("ThirdPartyPackage");
        String 	savepath = intent.getExtras().getString("CurrentPath");

        settingPreference.setSettingParam(Define.THIRD_PACKAGE, packageName);
        settingPreference.setSettingParam(Define.SAVE_PATH, savepath);

		uploadFile(savepath, strFileName, uploadUrl, context);

    }

	public boolean uploadFile(String path,String filename,String uploadUrl, Context context)
	{
		OkHttpClient okhttp = new OkHttpClient();
		File file = new File(path);
		if(path.isEmpty() || !file.exists())
			return false;
		FutureTask<Boolean> task = new FutureTask<>(()->
		{
			try
			{
				RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
						.addFormDataPart("file",filename,RequestBody.create(file , MediaType.parse("multipart/form-data")))
						.addFormDataPart("filename",filename)
						.build();
				ResponseBody responseBody = okhttp.newCall(
						new Request.Builder().post(body).url(uploadUrl).build()
				).execute().body();

				if(responseBody != null){
					((MainActivity)context).wpsPluginCallback.onCallback(1, new HashMap<>());
					return Boolean.parseBoolean(responseBody.string());
				}
				((MainActivity)context).wpsPluginCallback.onCallback(0, new HashMap<>());
				return false;
			}
			catch (IOException e)
			{
				e.printStackTrace();
				((MainActivity)context).wpsPluginCallback.onCallback(0, new HashMap<>());
				return false;
			}
		});
		try
		{
			new Thread(task).start();
			return task.get();
		}
		catch (ExecutionException | InterruptedException e)
		{
			e.printStackTrace();
			return false;
		}
	}
    
}